import 'dart:convert';

import 'connectivitytest_platform_interface.dart';
import './generated_bindings.dart';

import 'dart:ffi';
import 'package:ffi/ffi.dart';
import './define.dart';
export './define.dart';

final DynamicLibrary _dylib = DynamicLibrary.open('libconnect_plugin.so');
final NativeLibrary lib = NativeLibrary(_dylib);
typedef DeviceInfoCallback = Void Function(Pointer<Char> deviceInfo);

class Connectivitytest {
  Future<String?> getPlatformVersion() {
    return ConnectivitytestPlatform.instance.getPlatformVersion();
  }

  Future<void> StartDiscovery() async {
    await StopDiscovery();
    Future.delayed(const Duration(seconds: 1)).then((value) {
      int Function() fun = _dylib
          .lookup<NativeFunction<Int32 Function()>>('StartDiscovery')
          .asFunction();
      fun();
    });
    return;
  }

  Future<void> StopDiscovery() async {
    int Function() fun = _dylib
        .lookup<NativeFunction<Int32 Function()>>('StopDiscovery')
        .asFunction();
    fun();
    return;
  }

  Future<List<DeviceInfo>> GetAllDeviceInfo() async {
    final str = lib.GetAllDeviceInfo();

    List<dynamic> list = jsonDecode(str.toDartString());
    List<DeviceInfo> result = list
        .map((item) => DeviceInfo(
            uuid: item['uuid'],
            deviceName: item['deviceName'],
            deviceType: item['deviceType'],
            ip: item['ip'],
            port: item['port']))
        .toList();

    return result;
  }
}
